package com.getpebble.android.framework.appmessage;

import com.getpebble.android.framework.appmessage.AppMessage.AppMessageCommand;
import java.util.UUID;

public class AppLifecycleMessage {
    protected static UUID UUID_FETCH = new UUID(0, 0);
    protected Action mAction;
    protected RunState mRunState;
    protected UUID mUUID;

    public enum Action {
        UPDATE_RUN_STATE(1),
        FETCH_STATE(2);
        
        private int mCode;

        private Action(int code) {
            this.mCode = code;
        }

        public int getCode() {
            return this.mCode;
        }
    }

    public enum RunState {
        NOT_RUNNING((byte) 0),
        RUNNING((byte) 1),
        UNKNOWN((byte) -1);
        
        byte mStateValue;

        private RunState(byte stateValue) {
            this.mStateValue = stateValue;
        }

        public byte getStateValue() {
            return this.mStateValue;
        }

        public static RunState fromDictionaryValue(long value) {
            for (RunState command : values()) {
                if (((long) command.getStateValue()) == value) {
                    return command;
                }
            }
            return UNKNOWN;
        }
    }

    public AppLifecycleMessage(AppMessage appMessage) {
        this.mRunState = RunState.UNKNOWN;
        if (appMessage.getPebbleDictionary() != null) {
            Long stateValue = appMessage.getPebbleDictionary().getUnsignedInteger(Action.UPDATE_RUN_STATE.getCode());
            if (stateValue != null) {
                this.mRunState = RunState.fromDictionaryValue(stateValue.longValue());
            }
            this.mUUID = appMessage.getUuid();
        }
    }

    public static AppLifecycleMessage obtainFetchAppsMessage() {
        return new AppLifecycleMessage(Action.FETCH_STATE, UUID_FETCH, RunState.RUNNING);
    }

    public AppLifecycleMessage(UUID uuid, RunState runState) {
        this(Action.UPDATE_RUN_STATE, uuid, runState);
    }

    public AppLifecycleMessage(Action action, UUID uuid, RunState runState) {
        this.mRunState = RunState.UNKNOWN;
        if (action == null || uuid == null || runState == null) {
            throw new IllegalArgumentException("missing action, UUID or runState");
        }
        this.mAction = action;
        this.mUUID = uuid;
        this.mRunState = runState;
    }

    public RunState getRunState() {
        return this.mRunState;
    }

    public UUID getUUID() {
        return this.mUUID;
    }

    public AppMessage toAppMessage() {
        BinaryPebbleDictionary d = new BinaryPebbleDictionary();
        d.addUint8(this.mAction.getCode(), this.mRunState.getStateValue());
        return new AppMessage(AppMessage.getNextTransactionId(), this.mUUID, AppMessageCommand.PUSH, d);
    }
}
